package com.gosophia.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.gosophia.commons.exception.CommonException;



public class FileUpload {

	private static Log log=LogFactory.getLog(FileUpload.class);
	/**
	 * 文件上传
	 * 
	 * @param file
	 * @throws IOException
	 */
	public static String fileUpload(File file, String filePath,
			String fileName) throws IOException,CommonException {
		if(file.length()==0){
			if(log.isTraceEnabled()){
				log.error("上传的文件不存在或上传文件的内容为空");
			}
			throw new FileNotFoundException("上传的文件不存在或上传文件的内容为空");
		}
		// 获得文件
		String path = ServletActionContext.getServletContext().getRealPath(
				filePath);
		File dir = new File(path);
		// 判断此路径是否存在
		if (!dir.exists()) {
			dir.mkdir();
		}
		String newFileName = UUID.randomUUID() + fileName;
		String filepath = filePath + "/" + newFileName;
		BufferedOutputStream buffOutput = null;
		BufferedInputStream buffInput = null;

		try {

			FileInputStream inputStream = new FileInputStream(file);
			buffInput = new BufferedInputStream(inputStream);

			FileOutputStream outputStream = new FileOutputStream(new File(dir,
					newFileName));
			buffOutput = new BufferedOutputStream(outputStream);

			byte[] buf = new byte[4096];
			int len = -1;
			while ((len = buffInput.read(buf)) != -1) {
				buffOutput.write(buf, 0, len);
			}
		} finally {
			buffOutput.close();
			buffInput.close();
		}
		return filepath;
	}

	/**
	 * 上传多个文件
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String[] fileUploads(File[] files, String[] fileName)
			throws IOException {
		String defaultPath = "/upload";// 默认路径
		String[] filePath = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			filePath[i] = fileUpload(files[i], defaultPath, fileName[i]);

		}
		return filePath;
	}
	/**
	 * 文件上传(默认路径)
	 * @throws IOException 
	 */
	public static String fileUpload(File file,
			String fileFileName) throws IOException {
		String defaultFilePath="/upload";
		return fileUpload(file,defaultFilePath,fileFileName);
	}
}
